package com.gem.netty.message.robot;

import com.gem.entity.Room;
import com.gem.enums.MessageColorType;
import com.gem.factory.game.GameFactory;
import com.gem.factory.room.RoomFactory;
import com.gem.factory.user.UserFactory;
import com.gem.netty.entity.ClientContent;
import com.gem.netty.message.Message;
import com.gem.netty.session.GroupSession;
import com.gem.netty.session.GroupSessionFactory;
import com.gem.utils.R;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.List;
import java.util.UUID;

/**
 * Author: Xhy
 * CreateTime: 2023-02-06 17:01
 * 加入机器人
 */
public class AddRobot implements Message {


    @Override
    public void handler(ClientContent content) {
        ChannelHandlerContext ctx = content.getCtx();
        String roomId = content.getRoomId();
        String sendId = content.getSendId();
        Room room = RoomFactory.get(roomId);
        if (!room.verifyRoomOwner(sendId)) {
            ctx.writeAndFlush
                    (new TextWebSocketFrame(R.error()
                            .data("color", MessageColorType.SYSTEM_MESSAGE.type).message("只有房主才能添加机器人").type(content.getType()).toString()));
            return;
        }
        Integer robotLevel = content.getRobotLevel();
        if (robotLevel!=0 && robotLevel!=1){
            ctx.writeAndFlush
                    (new TextWebSocketFrame(R.error()
                            .data("color", MessageColorType.SYSTEM_MESSAGE.type).message("机器人分段只有新手和王者").type(content.getType()).toString()));
            return;
        }
        // 创建机器人id
        String robotId = UUID.randomUUID().toString();
        R r = RoomFactory.verifyJoin(roomId, robotId);
        if (!r.getState()){
            ctx.writeAndFlush
                    (new TextWebSocketFrame(R.error()
                            .data("color", MessageColorType.SYSTEM_MESSAGE.type).message(r.getMessage()).type(content.getType()).toString()));
            return;
        }
        RoomFactory.joinRobot(roomId, robotLevel,robotId);

        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        List<Channel> members = groupSession.getMembersChannel(roomId);
        groupSession.joinMember(roomId,robotId);

        GameFactory.notifyUsers(members,R.ok().data("color", MessageColorType.SYSTEM_MESSAGE.type)
                .message(UserFactory.get(sendId) + ":" +"添加了机器人：段位："+(robotLevel == 0 ? "新手" : "王者")).type(content.getType()),roomId);
    }

}
